<template>
	<view class="editInfo">
		<view class="form">
			<view class="inpItem">
				<view class="inpTitle">
					头像：
				</view>

				<view class="inpAvatar" @click="selectAvatar()">
					<!-- <view class="inpAvatar"> -->
					<image class="avatarImg" v-if="!form.avatar" src="@/static/images/my_avatar.png" mode=""></image>
					<image class="avatarImg" v-else :src="hname+form.avatar" mode=""></image>
				</view>
				<!-- <button size="mini" type="primary" open-type="chooseAvatar" @chooseavatar="getUserImg">
					获取微信头像
				</button> -->
			</view>
			<view class="inpItem">
				<view class="inpTitle">
					*昵称：
				</view>
				<view class="inpBox">
					<input class="inp" maxlength="10" @input="onInput" type="nickname" @blur="nameBlur()"
						v-model="form.username" placeholder="请输入" placeholder-class="pStyle">
				</view>
				<!-- <button size="mini" type="primary" open-type="chooseAvatar" @chooseavatar="getUserImg">
					获取微信昵称
				</button> -->
			</view>
			<view class="inpItem">
				<view class="inpTitle">
					手机号：
				</view>
				<view class="inpBox">
					{{setPhone}}
				</view>
			</view>
		</view>
		<view class="btnBox">
			<view class="btn">
				<view class="cancel" @click="cancel()">
					取消
				</view>
				<button class="confirm" :disabled="disabled" @click="submitForm()">
					确认
				</button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		editUserInfo,
		getUserInfo,
		wechatTextCheck,
		wechatMediaCheck
	} from "@/api/index.js"
	export default {
		data() {
			return {
				form: {
					username: "",
					avatar: "",
				},
				avatarUrl: '',
				userInfo: {
					phone: '12783891201'
				},
				userRes: {},
				disabled: '',
				hname: 'http://localhost:3000/'
			};
		},
		async onLoad() {
			let uInfo = uni.getStorageSync('mini-userinfo')
			if (uInfo) {
				this.userInfo = uInfo
				const userRes = await getUserInfo(this.userInfo.id)
				console.log(userRes.data, '?????????????????????????');
				if (userRes.statusCode == 200) {
					this.userRes = userRes.data.data.userInfo
					this.form.avatar = userRes.data.data.avatar?.replace(/\\/g, '\/')
					this.form.username = userRes.data.data.username
				}
			}

		},
		computed: {
			setPhone() {
				if (this.userInfo?.phone) {
					let pre = this.userInfo.phone.slice(0, 3)
					let next = this.userInfo.phone.slice(7, 11)
					return pre + '****' + next
				}
				return ''
			},

		},
		methods: {
			onInput(event) {
				// 获取输入框的值
				let value = event.target.value;
				// 移除字符串中的所有空格
				this.$nextTick(() => {
					this.form.username = value.replace(/\s+/g, '')
				});
			},
			async nameBlur() {
				if (this.form.username) {
					const textCheckRes = await wechatTextCheck({text:this.form.username})
					if(textCheckRes.data.statusCode==200){
						if(!textCheckRes.data.data.isSafe){
							this.form.username=''//若昵称违规，置空
							uni.showToast({
								title:'昵称违规，请重新输入',
								icon:'none'
							})
						}
					}
				}
			},
			getUserImg(e) {
				console.log(e);
				uni.uploadFile({
					url: `${uni.$http.baseUrl}/api/file-uploads/single`,
					method: "POST",
					filePath: e.detail.avatarUrl,
					name: 'file',
					header: {
						"content-type": 'multipart/form-data',
					},
					success: res => {
						console.log(res, '长');
						console.log(JSON.parse(res.data), '成功后的结果');
						let data = JSON.parse(res.data)

						this.form.avatar = data.file.path
					},
					fail: err => {
						uni.showToast({
							title: '文件上传失败',
							icon: 'none'
						})
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			},
			selectAvatar() { //图片上传
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: (res) => {
						console.log(res, JSON.stringify(res.tempFilePaths));
						uni.uploadFile({
							url: `${uni.$http.baseUrl}/api/upload/image`,
							method: "POST",
							filePath: res.tempFilePaths[0],
							name: 'image',
							header: {
								"content-type": 'multipart/form-data',
							},
							success: async res => {
								console.log(res, '长');
								console.log(JSON.parse(res.data), '成功后的结果');
								let data = JSON.parse(res.data)
								const media=this.hname+data.data.path.fileurl
								const mediaCheckRes = await wechatMediaCheck({media})
								if(mediaCheckRes.statusCode==200){
									if(!mediaCheckRes.data.isSafe){
										uni.showToast({
											title:'头像违规，请重新上传',
											icon:'none'
										})
									}else{
										this.$nextTick(()=>{
											this.form.avatar = data.data.fileUrl
										})
									}
								}
							},
							fail: err => {
								uni.showToast({
									title: '文件上传失败',
									icon: 'none'
								})
							},
							complete: () => {
								uni.hideLoading()
							}
						})
					}
				});
			},
			async submitForm() { //表单提交
				this.disabled = true
				if (this.form.username === '' || this.form.username == null) {
					this.disabled = false
					return uni.showToast({
						title: '请输入昵称',
						icon: 'none',
					})
				}
				let params = {
					avatar: this.form.avatar,
					username: this.form.username,
				}
				console.log(params);
				const submitRes = await editUserInfo(this.userInfo.id, params)
				console.log(submitRes, 'submitRes.isok');
				if (submitRes.statusCode==200) {
					uni.showToast({
						title: '编辑成功',
						icon: 'none',
						duration: 1000,
					})
					try {
						const userRes = await getUserInfo(this.userInfo.id)
						// 检查 key 是否存在，如果存在先删除
						if (uni.getStorageSync('mini-userinfo')) {
							uni.removeStorageSync('mini-userinfo');
						}
						// 存储新数据
						uni.setStorageSync('mini-userinfo', userRes.data.data);
					} catch (e) {
						// 处理错误
						console.error('存储失败', e);
					}
					setTimeout(() => {
						uni.navigateBack()
					}, 1000)
				} else {
					uni.showToast({
						title: submitRes.data.message,
						duration: 1500,
						icon: 'none'
					})
					this.disabled = false
				}
				// console.log(params, '表单', submitRes);
			},
			cancel() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.editInfo {
		.form {
			font-size: 32rpx;
			width: 100%;

			.pStyle {
				font-size: 32rpx;
				font-weight: 250;
				color: rgba(0, 0, 0, 0.9);
				opacity: 0.3;
			}

			.inpItem {
				width: 100%;
				height: 112rpx;
				background: #FFFFFF;
				box-shadow: inset 0px -0.5px 0px 0px rgba(0, 0, 0, 0.1);
				padding: 0 32rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.inpTitle {
					width: 180rpx;
					font-size: 32rpx;
					font-weight: 300;
				}

				.inpBox {
					flex: 1;
					display: flex;
					align-items: center;
					color: #000000;
					font-weight: normal;

					.inp {
						width: 100%;
						height: 80rpx;
						font-size: 28rpx;
					}

					.baseImg {
						width: 240rpx;
						height: 90rpx;
					}

				}

				.inpAvatar {
					flex: 1;
					display: flex;
					justify-content: flex-end;

					// margin-right: 10rpx;
					.avatarImg {
						width: 70rpx;
						height: 70rpx;
						border-radius: 50%;
					}
				}

				.selectBox {
					flex: 1;
					display: flex;
					justify-content: space-between;
					align-items: center;
					height: 100%;

					.inp {
						width: 100%;
						height: 80rpx;
						font-size: 28rpx;
					}

					.datePicker {
						width: 100%;

						// height: 100%;
						// display: flex;
						// align-items: center;
						// justify-content: space-between;
						.uni-input {
							height: 80rpx;
							display: flex;
							align-items: center;
							justify-content: space-between;
						}
					}
				}
			}
		}


		.btnBox {
			width: 100%;
			position: fixed;
			bottom: 0;
			background-color: #fff;
			height: 160rpx;

			.btn {
				width: 100%;
				height: 160rpx;
				padding: 36rpx 114rpx 0;
				display: flex;
				justify-content: space-between;

				.confirm,
				.cancel {
					width: 240rpx;
					height: 80rpx;
					text-align: center;
					line-height: 80rpx;
					border-radius: 8rpx;
					font-size: 34rpx;
				}

				.confirm {
					color: #FFFFFF;
					background: #000000;
				}

				.cancel {
					border: 1px solid #000000;
					color: #000000;
					background: rgba(255, 255, 255, 0.15);
				}
			}
		}
	}
</style>